<?php

class Admin_OperationControllerController extends Model3_Controller
{

    public function init()
    {
        if (!Model3_Auth::isAuth())
        {
            $this->redirect('Index/index');
        }
    }

    /**
     * Acción que se encarga de asignar un controlador de operaciones a un vehículo.
     */
    public function indexAction()
    {
        $em = $this->getEntityManager('DefaultDb');
        $userRepository = $em->getRepository('DefaultDb_Entities_User');
        $controllers = $userRepository->getActiveOperationControllers();
        $breadcrumb = array();

        $this->view->whereAmI = $breadcrumb;
        $this->view->controllers = $controllers;
        $this->view->setTemplate('Responsive-3.0');
        $this->view->title = 'Controlador de operaciones';
        $this->view->description = 'Administración de controlador de operaciones';
    }

    /**
     * Validamos que el id del controlador se reciba por params y que ese
     * controlador exista y se encuentre activo. 
     * @return DefaultDb_Entities_User Si el controlador de operaciones existe y
     * se encuentra vigente. FALSE en caso de que el controlador de operaciones
     * no exista o se encuentre inactivo, en este caso se realiza una redireccion
     * al index del controlador de operaciones.
     */
    private function validateController()
    {
        $controllerId = $this->getRequest()->getParam('id');
        if ($controllerId !== null)
        {
            $em = $this->getEntityManager('DefaultDb');
            $userRepository = $em->getRepository('DefaultDb_Entities_User');
            $criteria = array(
                'id' => $controllerId,
                'status' => DefaultDb_Entities_User::STATUS_ACTIVE
            );
            $controller = $userRepository->findOneBy($criteria);
            if ($controller instanceof DefaultDb_Entities_User)
            {
                $controllers = $userRepository->getActiveOperationControllers();
                $this->view->controllers = $controllers;
                return $controller;
            }
        }
        $this->redirect('Admin/OperationController/index');
        return false;
    }

    /**
     * Listamos los conductores asignados a un controlador de operaciones
     */
    public function driversAction()
    {
        $request = $this->getRequest();
        if ($request->isPost() === true)
        {
            $params = $request->getPost();
            $this->runActionDrive($params);
        }
        $controller = $this->validateController();
        if ($controller instanceof DefaultDb_Entities_User)
        {
            $em = $this->getEntityManager('DefaultDb');
            $userRepository = $em->getRepository('DefaultDb_Entities_User');
            $criteria = array(
                'parent' => $controller,
                'type' => DefaultDb_Entities_User::USER_DRIVER,
                'status' => DefaultDb_Entities_User::STATUS_ACTIVE
            );
            $controllers = $userRepository->getActiveOperationControllers();
            $drivers = $userRepository->findBy($criteria);
            $breadcrumb = array('Controlador de operaciones' => array('action' => 'index'));
            $this->view->setTemplate('Responsive-3.0');
            $this->view->em = $em;
            $this->view->whereAmI = $breadcrumb;
            $this->view->controller = $controller;
            $this->view->drivers = $drivers;
            $this->view->controllers = $controllers;
            $this->view->title = 'Conductores asignados';
            $this->view->description = 'Administración de controlador de operaciones';
        }
    }

    /**
     * Asignamos un conductor a un controlador de operaciones
     */
    public function addDriverAction()
    {
        $controller = $this->validateController();
        if ($controller instanceof DefaultDb_Entities_User)
        {
            $em = $this->getEntityManager('DefaultDb');
            $userRepository = $em->getRepository('DefaultDb_Entities_User');
            $breadcrumb = array(
                'Controlador de operaciones' => array('action' => 'index'),
                'Conductores asignados' => $this->view->url(array('action' => 'drivers'), true),
            );
            $criteria = array(
                'type' => DefaultDb_Entities_User::USER_DRIVER,
                'status' => DefaultDb_Entities_User::STATUS_ACTIVE
            );
            $drivers = $userRepository->findBy($criteria);
            $drivers = array_filter($drivers, function($driver) use($controller) {
                        if ($driver->getParent() === null)
                        {
                            return true;
                        }
                        return $driver->getParent()->getId() != $controller->getId();
                    });
            $this->view->setTemplate('Responsive-3.0');
            $this->view->em = $em;
            $this->view->whereAmI = $breadcrumb;
            $this->view->controller = $controller;
            $this->view->drivers = $drivers;
            $this->view->title = 'Asignar conductor';
            $this->view->description = 'Administración de controlador de operaciones';
        }
    }

    /**
     * Validamos parametros y realizamos la accion adecuada.
     */
    private function runActionDrive($params)
    {
        if (isset($params['action']) === true)
        {
            $em = $this->getEntityManager('DefaultDb');
            $userRepository = $em->getRepository('DefaultDb_Entities_User');
            $action = $params['action'];
            switch ($action)
            {
                case 'add':
                    $args = array(
                        'controller' => FILTER_VALIDATE_INT,
                        'driver' => FILTER_VALIDATE_INT,
                    );
                    $filterParams = filter_input_array(INPUT_POST, $args);
                    if (array_search(false, $filterParams) === false)
                    {
                        $criteria = array(
                            'id' => $filterParams['controller'],
                            'status' => DefaultDb_Entities_User::STATUS_ACTIVE,
                        );
                        $controller = $userRepository->findOneBy($criteria);
                        $criteria['id'] = $filterParams['driver'];
                        $driver = $userRepository->findOneBy($criteria);
                        if ($controller instanceof DefaultDb_Entities_User && $driver instanceof DefaultDb_Entities_User)
                        {
                            $driver->setParent($controller);
                            $em->persist($driver);
                            $em->flush();
                            /**
                             * @todo falta agregar log de asignacion de conductor a controlador
                             */
                        }
                    }
                    break;
                case 'delete':
                    $args = array(
                        'driver' => FILTER_VALIDATE_INT,
                    );
                    $filterParams = filter_input_array(INPUT_POST, $args);
                    if (array_search(false, $filterParams) === false)
                    {
                        $criteria = array(
                            'id' => $filterParams['driver'],
                            'status' => DefaultDb_Entities_User::STATUS_ACTIVE,
                        );
                        $driver = $userRepository->findOneBy($criteria);
                        if ($driver instanceof DefaultDb_Entities_User)
                        {
                            $driver->setParent(null);
                            $em->persist($driver);
                            $em->flush();
                            /**
                             * @todo falta agregar log de asignacion de conductor a controlador
                             */
                        }
                    }
                    break;
            }
        }
    }

    public function vehiclesAction()
    {
        $controller = $this->validateController();
        if ($controller instanceof DefaultDb_Entities_User)
        {
            $em = $this->getEntityManager('DefaultDb');
            $vehiclesRepository = $em->getRepository('DefaultDb_Entities_Vehicle');
            $vehicles = $vehiclesRepository->getByController($controller);
            $breadcrumb = array('Controladores' => array('action' => 'index'));
            $this->view->setTemplate('Responsive-3.0');
            $this->view->em = $em;
            $this->view->controller = $controller;
            $this->view->vehicles = $vehicles;
            $this->view->whereAmI = $breadcrumb;
            $this->view->title = 'Vehículos asignados';
            $this->view->description = 'Administración de controlador de operaciones';
        }
    }

    public function routesAction()
    {
        $request = $this->getRequest();
        if ($request->isPost() === true)
        {
            $params = $request->getPost();
            $this->runActionRoute($params);
        }
        $controller = $this->validateController();
        if ($controller instanceof DefaultDb_Entities_User)
        {
            $em = $this->getEntityManager('DefaultDb');
            $routesRepository = $em->getRepository('DefaultDb_Entities_Route');
            $criteria = array(
                'status' => DefaultDb_Entities_Route::STATUS_ACTIVE,
                'close' => DefaultDb_Entities_Route::CLOSE,
                'controller' => $controller,
            );
            $routes = $routesRepository->findBy($criteria);
            $breadcrumb = array('Controladores' => array('action' => 'index'));
            $this->view->setTemplate('Responsive-3.0');
            $this->view->em = $em;
            $this->view->controller = $controller;
            $this->view->routes = $routes;
            $this->view->whereAmI = $breadcrumb;
            $this->view->title = 'Rutas asignadas';
            $this->view->description = 'Administración de controlador de operaciones';
        }
    }

    public function addRouteAction()
    {
        $controller = $this->validateController();
        if ($controller instanceof DefaultDb_Entities_User)
        {
            $em = $this->getEntityManager('DefaultDb');
            $routesRepository = $em->getRepository('DefaultDb_Entities_Route');
            $breadcrumb = array(
                'Controlador de operaciones' => array('action' => 'index'),
                'Rutas asignadas' => $this->view->url(array('action' => 'routes'), true),
            );
            $criteria = array(
                'status' => DefaultDb_Entities_Route::STATUS_ACTIVE,
                'close' => DefaultDb_Entities_Route::CLOSE,
            );
            $routes = $routesRepository->findBy($criteria);
            $routes = array_filter($routes, function($route) use($controller) {
                        if ($route->getController() === null)
                        {
                            return true;
                        }
                        return $route->getController()->getId() != $controller->getId();
                    });
            $this->view->setTemplate('Responsive-3.0');
            $this->view->em = $em;
            $this->view->whereAmI = $breadcrumb;
            $this->view->controller = $controller;
            $this->view->routes = $routes;
            $this->view->title = 'Asignar ruta';
            $this->view->description = 'Administración de controlador de operaciones';
        }
    }
    
    private function runActionRoute($params)
    {
        if (isset($params['action']) === true)
        {
            $em = $this->getEntityManager('DefaultDb');
            $userRepository = $em->getRepository('DefaultDb_Entities_User');
            $routesRepository = $em->getRepository('DefaultDb_Entities_Route');
            $action = $params['action'];
            switch ($action)
            {
                case 'add':
                    $args = array(
                        'controller' => FILTER_VALIDATE_INT,
                        'route' => FILTER_VALIDATE_INT,
                    );
                    $filterParams = filter_input_array(INPUT_POST, $args);
                    if (array_search(false, $filterParams) === false)
                    {
                        $criteria = array(
                            'id' => $filterParams['controller'],
                            'status' => DefaultDb_Entities_User::STATUS_ACTIVE,
                        );
                        $controller = $userRepository->findOneBy($criteria);
                        $criteria = array(
                            'id' => $filterParams['route'],
                            'status' => DefaultDb_Entities_Route::STATUS_ACTIVE,
                        );
                        $route = $routesRepository->findOneBy($criteria);
                        if ($controller instanceof DefaultDb_Entities_User && $route instanceof DefaultDb_Entities_Route)
                        {
                            $route->setController($controller);
                            $em->persist($route);
                            $em->flush();
                            /**
                             * @todo falta agregar log de asignacion de conductor a controlador
                             */
                        }
                    }
                    break;
                case 'delete':
                    $args = array(
                        'route' => FILTER_VALIDATE_INT,
                    );
                    $filterParams = filter_input_array(INPUT_POST, $args);
                    if (array_search(false, $filterParams) === false)
                    {
                        $criteria = array(
                            'id' => $filterParams['route'],
                            'status' => DefaultDb_Entities_Route::STATUS_ACTIVE,
                        );
                        $route = $routesRepository->findOneBy($criteria);
                        if ($route instanceof DefaultDb_Entities_Route)
                        {
                            $route->setController(null);
                            $em->persist($route);
                            $em->flush();
                            /**
                             * @todo falta agregar log de asignacion de conductor a controlador
                             */
                        }
                    }
                    break;
            }
        }
    }

}